package com.golxen.framework.netty;


import com.golxen.framework.PBPacket.PBPacket;
import com.google.protobuf.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import org.apache.commons.lang3.StringUtils;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ServerClientProtoBufEncoder extends MessageToMessageEncoder<PBPacket> {

	String flag;

	public ServerClientProtoBufEncoder(String flag) {
		this.flag = StringUtils.reverse(flag);
	}

	@Override
	protected void encode(ChannelHandlerContext ctx, PBPacket msg, List<Object> out) throws Exception {
		Object object = msg.getMyMsg();
		if (object != null && msg.getMyMsg() instanceof ArrayList) {
			ArrayList<PBPacket> messageBuffer = (ArrayList<PBPacket>)msg.getMyMsg();
			for (PBPacket message : messageBuffer) {
				encodeMessage(ctx, message, out);
			}
		} else {
			encodeMessage(ctx, msg, out);
		}
	}

	private void encodeMessage(ChannelHandlerContext ctx, PBPacket message, List<Object> out) {
		Message pbMessage = message.getMessage();
		int size = PBPacket.HDR_SIZE;
		if (pbMessage != null) {
			size = PBPacket.HDR_SIZE + pbMessage.getSerializedSize();
		} else {
			byte[] bytes = message.getBytes();
			if (bytes != null) {
				size = PBPacket.HDR_SIZE + bytes.length;
			}
		}


		ByteBuf buffer = ctx.alloc().buffer(size);
		message.writeHeader(size, buffer);
		out.add(buffer);
	}
}
